package cr

import (
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/beans"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/grpcs"
	"gitee.com/shiqiyue/bi-client"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/grpcsrv"
	"gitee.com/shiqiyue/xd-bi/internal/pkg/instance"
	"google.golang.org/grpc"
	"net"
)

//grpc初始化
func GrpcInit(errc chan error, registerGrpcServer func(grpcServer *grpc.Server)) {
	config := instance.GetConfig()
	kitLog := instance.GetKitLog()

	// 监听端口
	grpcAddress := config.Grpc.Address
	lis, err := net.Listen("tcp", grpcAddress)
	asserts.Nil(err, err)
	// 初始化grpc服务
	var opts []grpc.ServerOption = grpcs.DefaultServerOptions(grpcs.ServerOptionConfig{
		Logger:        instance.GetAppLog(),
		RbacPublicKey: instance.GetAuthViper().GetString("rbac.publicKey"),
	})
	// 设置通用拦截器

	grpcServer := grpc.NewServer(opts...)
	// 注册grpc服务
	registerGrpcServer(grpcServer)
	// 启动grpc服务器
	go func() {
		_ = kitLog.Log("restfulTrans", "GRPC", "addr", grpcAddress)
		errc <- grpcServer.Serve(lis)
	}()
}

// 注册grpc服务
func registerGrpcServer(grpcServer *grpc.Server) {
	srv := &grpcsrv.BiSrv{}
	err := beans.ProvideBean(srv)
	asserts.Nil(err, err)

	// populate beans
	err = beans.Populate()
	asserts.Nil(err, err)

	bi.RegisterBiRpcServer(grpcServer, srv)
}
